package com.scau.phr.business.bmi.controller;

import com.scau.phr.business.auth.domain.Session;
import com.scau.phr.business.auth.service.SessionService;
import com.scau.phr.business.auth.service.SimpleSessionServiceImpl;
import com.scau.phr.business.bmi.service.BmiService;
import com.scau.phr.common.exceptions.ErrorCode;
import com.scau.phr.common.exceptions.ServiceException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.cglib.core.Local;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

/**
 * @author yuzhiyi
 * @date 2018/8/15 10:00
 */
@RestController
@RequestMapping("/bmi/")
public class BmiController {

	@Autowired
	private BmiService bmiService;

	@Autowired @Qualifier(SimpleSessionServiceImpl.NAME)
	private SessionService sessionService;

	/**
	 * 添加新的体重信息
	 * @param weight 体重
	 * @param dateTime 日期，一定要yyyy-mm-ddThh-mm-ss
	 * @return
	 */
	@RequestMapping("/weight/add")
	public Object addNewWeightRecord(@RequestParam("weight") Double weight,@RequestParam(value = "datetime",required = false) String dateTime){
		LocalDateTime time;
		if (dateTime != null){
			time = LocalDateTime.parse(dateTime, DateTimeFormatter.ISO_DATE_TIME);
		}else{
			time = LocalDateTime.now();
		}
		String tel = getCurrentUserName();
		bmiService.addWeightRecord(tel,weight,time);
		return true;
	}

	/**
	 * 更新身高信息
	 */
	@RequestMapping("height/update")
	public Object updateUserHeight(@RequestParam("height")Integer height){
		bmiService.updateHeight(getCurrentUserName(),height);
		return true;
	}


	@RequestMapping("get")
	public Object getBmiDate(){
		return bmiService.getWeightHistory(getCurrentUserName());
	}


	private String getCurrentUserName(){
		Session session = sessionService.getCurrentSession();
		if (session == null){
			throw new ServiceException(ErrorCode.AUTH_ERROR,"Token无效或者过期");
		}
		return session.getUsername();
	}



}
